import {
  createPopup,
  getPopupById,
  updatePopup,
  updatePopupPositition,
  closePopup,
} from "../popup/index";
import { LayerType } from "../layer/layerManage.ts";

// 定义一个函数clusterLayer，用于生成一个包含设备信息的HTML字符串
function clusterLayer(options: any) {
  // 将options.data解析为JSON对象
  options.data = JSON.parse(options.data);
  // 返回一个包含设备信息的HTML字符串
  return `<div style="
        background: #FFFFFF;
        border-radius: 6px;
        padding: 8px;
        width: 200px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        font-family: Arial, sans-serif;
      ">
        <div style="
          display: flex;
          align-items: center;
          gap: 4px;
          padding-bottom: 6px;
          border-bottom: 1px solid #F0F0F0;
        ">
          <div style="
            background: #437EF1;
            color: white;
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 10px;
          ">设备信息</div>
          <div style="
            color: #437EF1;
            font-size: 12px;
            font-weight: 500;
          ">${options.label || '永发乡红石村'}</div>
        </div>
        <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 4px; text-align: center;">
          <div>
            <div style="color: #909399; font-size: 9px;">设备ID</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${options.data.devId || '715'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备类型</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${options.data.devType || '火箭类'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备名称</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${options.data.devName || '火箭发射架'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备型号</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${options.data.devModel || 'WR-98'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">设备状态</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${options.data.devStatus || '在用'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">检查状态</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${options.data.devCheckStatus || '合格'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">经度</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${Number(options.data.pointLongi).toFixed(6) || '124.93611111111112'}
            </div>
          </div>
          <div>
            <div style="color: #909399; font-size: 9px;">纬度</div>
            <div style="color: #437EF1; font-size: 11px; font-weight: 500; font-family: DIN;">
              ${Number(options.data.pointLati).toFixed(6) || '43.77916666666667'}
            </div>
          </div>
        </div>
      </div>`;
}

/**
 * 加载聚合源
 * @param map - 地图实例
 * @param sourceName - 源名称
 * @param data - 地理JSON数据
 */
export const loadClusterSource = (map: any, sourceName: string, data: any) => {
  try {
    // 检查源是否已存在，避免重复添加
    if (!map.getSource(`${sourceName}_source`)) {
      // 添加源
      map.addSource(`${sourceName}_source`, {
        type: "geojson",
        data,
        cluster: true,
        clusterRadius: 30,
        clusterMaxZoom: 14, // 在第14级缩放时显示单个标记
      });
      // 加载聚合图层
      loadClusterLayer(map, `${sourceName}_layer`, `${sourceName}_source`);
    }
  } catch (error) {
    console.error(`加载聚合源 ${sourceName} 时出错:`, error);
  }
};

/**
 * 加载聚合图层
 * @param map - 地图实例
 * @param layerName - 图层名称
 * @param sourceName - 源名称
 */
export const loadClusterLayer = (map: any, layerName: string, sourceName: string) => {
  try {
    // 检查图层是否已存在，避免重复添加
    if (!map.getLayer(layerName)) {
      // 添加实际的点（显示真实标记和图片）
      map.addLayer({
        id: `${layerName}_point`,
        type: "symbol",
        source: sourceName,
        filter: ["!has", "point_count"], // 过滤聚合点，显示真实的标记
        layout: {
          "icon-image": ["get", "imageName"], // 使用自定义图标
          "icon-size": 0.19, // 调整图标大小
          "text-field": "{label}", // 显示名称或其他字段
          "text-font": ["MicrosoftYaHei"],
          "text-size": 10, // 调整字体大小
          "text-offset": [0.5, 2.5], // 调整文字偏移
        },
      });

      // 添加聚合层
      map.addLayer({
        id: layerName,
        type: "symbol",
        source: sourceName,
        layout: {
          "icon-size": ["case", ["has", "point_count"], 0.2, 0.1], // 调整聚合点图标大小
          "icon-image": [
            "case",
            ["has", "point_count"], // 条件1
            "position", // 结果1
            ["get", "defaultIcon"],
          ], // 聚合点图标
          "text-field": ["get", "point_count_abbreviated"], // 聚合点数量
          "text-font": ["MicrosoftYaHei"], // 聚合点字体
          "text-offset": [0.5, -0.05], // 调整聚合点数量偏移
          "text-size": 18, // 调整聚合点数量大小
          "icon-ignore-placement": true, // 聚合点图标忽略覆盖
        },
        paint: {
          "text-color": "#FFFFFF", // 文字颜色
          // "text-halo-width": 1, // 背景宽度
          // "text-halo-color": "rgba(0, 0, 0, 0.8)", // 背景颜色
          // "text-halo-blur": 0.5, // 背景模糊
        },
      });
    }
  } catch (error) {
    console.error(`加载聚合图层 ${layerName} 时出错:`, error);
  }
};

/**
 * 删除聚合图层
 * @param map - 地图实例
 * @param layerName - 图层名称
 */
export const removeClusterLayer = (map: any, layerName: string) => {
  try {
    if (map.getLayer(`${layerName}_layer`)) {
      map.removeLayer(`${layerName}_layer`);
    }
    if (map.getLayer(`${layerName}_layer_point`)) {
      map.removeLayer(`${layerName}_layer_point`);
    }
    // 删除Popup
    closePopup("cluster_popup");
  } catch (error) {
    console.error(`删除聚合图层 ${layerName} 时出错:`, error);
  }
};

/**
 * 删除聚合源
 * @param map - 地图实例
 * @param sourceName - 源名称
 */
export const removeClusterSource = (map: any, sourceName: string) => {
  try {
    if (map.getSource(`${sourceName}_source`)) {
      map.removeSource(`${sourceName}_source`);
    }
  } catch (error) {
    console.error(`删除聚合源 ${sourceName} 时出错:`, error);
  }
};

/**
 * 处理点击事件
 * @param map - 地图实例
 * @param layerId - 图层ID
 */
const handleClick = (map: any, layerId: string) => {
  map.on("click", layerId, (e: any) => {
    try {
      // 获取点击位置的元素
      const features = map.queryRenderedFeatures(e.point, { layers: [layerId] });
      if (features.length > 0) {
        const properties = features[0].properties;
        const coordinates = features[0].geometry.coordinates;
        console.log(properties);

        if (!properties.data) {
          closePopup("cluster_popup");
          return;
        }
        let popup = getPopupById("cluster_popup");
        // 如果popup不存在，创建popup
        if (!popup) {
          // 如果 popup 不存在，创建 popup
          popup = createPopup(
            map,
            "cluster_popup",
            coordinates,
            clusterLayer(properties)
          );
        }

        updatePopupPositition("cluster_popup", coordinates);
        updatePopup(
          popup,
          clusterLayer(properties)
        );
      } else {
        closePopup("cluster_popup");
      }
    } catch (error) {
      console.error("处理点击事件时出错:", error);
    }
  });
};

/**
 * 处理聚合开关
 * @param map - 地图实例
 * @param sourceName - 源名称
 * @param data - 地理JSON数据
 * @param isCluster - 是否开启聚合
 */
export const toggleCluster = (map: any, sourceName: string, data: any, isCluster: boolean) => {
  if (isCluster) {
    // 开启聚合
    loadClusterSource(map, sourceName, data);
    // 移除实际点点击事件
    map.off("click", `${sourceName}_non_cluster_layer`);
    // 绑定聚合点点击事件
    handleClick(map, `${sourceName}_layer`);
    handleClick(map, `${sourceName}_layer_point`);
  } else {
    // 关闭聚合
    removeClusterLayer(map, `${sourceName}_layer`);
    removeClusterSource(map, sourceName);
    // 移除聚合点点击事件
    map.off("click", `${sourceName}_layer`);
    map.off("click", `${sourceName}_layer_point`);

    // 加载实际点的源和图层
    if (!map.getSource(`${sourceName}_non_cluster_source`)) {
      map.addSource(`${sourceName}_non_cluster_source`, {
        type: "geojson",
        data,
      });
    }

    if (!map.getLayer(`${sourceName}_non_cluster_layer`)) {
      map.addLayer({
        id: `${sourceName}_non_cluster_layer`,
        type: "symbol",
        source: `${sourceName}_non_cluster_source`,
        layout: {
          "icon-image": ["get", "imageName"],
          "icon-size": 0.19,
          "text-field": "{label}",
          "text-font": ["MicrosoftYaHei"],
          "text-size": 10,
          "text-offset": [0.5, 2.5],
        },
      });
    }
    // 绑定实际点点击事件
    handleClick(map, `${sourceName}_non_cluster_layer`);
  }
};

/**
 * 释放资源
 * @param map - 地图实例
 * @param sourceName - 源名称
 */
export const releaseResources = (map: any, sourceName: string) => {
  // 移除聚合相关图层
  if (map.getLayer(`${sourceName}_layer`)) {
    map.removeLayer(`${sourceName}_layer`);
  }
  if (map.getLayer(`${sourceName}_layer_point`)) {
    map.removeLayer(`${sourceName}_layer_point`);
  }

  // 移除聚合源
  if (map.getSource(`${sourceName}_source`)) {
    map.removeSource(`${sourceName}_source`);
  }

  // 移除实际点相关图层
  if (map.getLayer(`${sourceName}_non_cluster_layer`)) {
    map.removeLayer(`${sourceName}_non_cluster_layer`);
  }

  // 移除实际点源
  if (map.getSource(`${sourceName}_non_cluster_source`)) {
    map.removeSource(`${sourceName}_non_cluster_source`);
  }

  // 移除所有点击事件监听器
  map.off("click", `${sourceName}_layer`);
  map.off("click", `${sourceName}_layer_point`);
  map.off("click", `${sourceName}_non_cluster_layer`);

  // 关闭Popup
  closePopup("cluster_popup");
};

/**
 * 修改实际点的属性
 * @param map - 地图实例
 * @param sourceName - 源名称
 * @param properties - 要修改的属性对象，例如 { "icon-size": 0.2, "text-size": 12 }
 */
export const updateActualPointsProperties = (map: any, sourceName: string, properties: any) => {
  const layerId = `${sourceName}_non_cluster_layer`;
  if (map.getLayer(layerId)) {
    map.setLayoutProperty(layerId, "icon-size", properties["icon-size"]);
    // 这里可以扩展更多属性的修改，例如 text-size, text-offset 等
    if (properties["text-size"]) {
      map.setLayoutProperty(layerId, "text-size", properties["text-size"]);
    }
    if (properties["text-offset"]) {
      map.setLayoutProperty(layerId, "text-offset", properties["text-offset"]);
    }
    // 以此类推，根据实际需求添加更多属性的修改逻辑
  }
};